import logging
import wsgiref.handlers
import os
import re
import random
import simplejson

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db

#   Model Classes   #
#___________________#

class Member(db.Model):
  version = db.DateTimeProperty(auto_now = True)

  iso = db.StringProperty()
  name = db.StringProperty()
  formal_name = db.StringProperty()
  location = db.GeoPtProperty()
  wto_url = db.StringProperty()
  tags = db.ListProperty(db.Category)
  # Is this a real country, or a synthetic org like the EU?
  is_country = db.BooleanProperty()
  note = db.StringProperty()

  # stats
  hdi = db.IntegerProperty()
  population = db.IntegerProperty()

class Group(db.Model):
  version = db.DateTimeProperty(auto_now = True)

  # Normal name for reference
  name = db.StringProperty()
  # If necessary, the complete, formal name
  formal_name = db.StringProperty()
  created = db.DateProperty()
  active = db.BooleanProperty()
  tags = db.ListProperty(db.Category)

class Meeting(db.Model):
  version = db.DateTimeProperty(auto_now = True)

  host = db.ReferenceProperty(Member)
  location = db.ListProperty(str)
  group = db.ReferenceProperty(Group)
  attendees = db.ListProperty(db.Key)
  # [ "UK", "London", "Buckingham Palace", "back-left corner" ]

  tags = db.ListProperty(db.Category)

class Document(db.Model):
  description = db.StringProperty()
  url = db.LinkProperty()

class Membership(db.Model):
  member = db.ReferenceProperty(Member)
  group = db.ReferenceProperty(Group)
  chair = db.BooleanProperty()
  start = db.DateProperty()
  end = db.DateProperty()
  active = db.BooleanProperty()

#   JSON Endpoints  #
#___________________#

class MemberList(webapp.RequestHandler):
  def get(self):
    members = Member.all()
    result = [member.iso for member in members]
    self.response.out.write(simplejson.dumps(result))

class MemberDetails(webapp.RequestHandler):
  def get(self):
    members = Member.all()
    result = [member for member in members]
    self.response.out.write(simplejson.dumps(result))

class MemberGroups(webapp.RequestHandler):
  def get(self):
    iso = self.request.get("iso"),
    memberships = Memberships.all()
    memberships.filter("member =", iso)
    memberships.filter("active =", True)

    result = [memberships.group.name for membership in memberships]
    self.response.out.write(simplejson.dumps(result))

class GroupList(webapp.RequestHandler):
  def get(self):
    groups = Groups.all()
    result = [group.name for group in groups]
    self.response.out.write(simplejson.dumps(result))

class GroupDetails(webapp.RequestHandler):
  def get(self):
    groups = Group.all()
    result = [group for group in groups]
    self.response.out.write(simplejson.dumps(result))

class GroupMembers(webapp.RequestHandler):
  def get(self):
    #group = self.request.get("group"),
    #memberships = Memberships.all()
    #memberships.filter("group =", group)
    #memberships.filter("active =", True)

    #result = [memberships.member.iso for membership in memberships]
    #self.response.out.write(simplejson.dumps(result))

    self.response.out.write("Getting group '%s'..." % self.request.get("group"))

    groups = Group.all()
    groups.filter("name =", self.request.get("group"))
    group = groups.fetch(1)[0]
    self.response.out.write("Got it.<br>")

    for iso in self.request.get("isos").split(":"):
      self.response.out.write("Want iso '%s'.." % iso)
      members = Member.all()
      members.filter("iso =", iso)
      member = members.fetch(1)[0]

      m = Membership(member = member,
                     group = group,
                     active = True)
      m.put()

      self.response.out.write(".saved.<br>")


class RootPage(webapp.RequestHandler):
  def get(self):
    self.redirect('/Browser')

class TemplatePage(webapp.RequestHandler):
  def get(self):
    pass

class MainPage(webapp.RequestHandler):
  def get(self):
    curUser = users.get_current_user()

    #if not curUser:
    #  self.redirect(users.create_login_url(self.request.uri))
    #  return
    
    path = os.path.join(os.path.dirname(__file__), 'templates/browser.html')
    self.response.out.write(template.render(path, None))


def main():
  application = webapp.WSGIApplication(
                                       [
                                        ('/', RootPage),
                                        ('/Browser', MainPage),
                                        ('/Template/.*', TemplatePage),
                                        ('/MemberList', MemberList),
                                        ('/MemberDetails', MemberDetails),
                                        ('/MemberGroups', MemberGroups),
                                        ('/GroupList', GroupList),
                                        ('/GroupDetails', GroupDetails),
                                        ('/GroupMembers', GroupMembers),
                                       ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
